<template>
  <div class="app-container question-new">
    <el-card>
      <div slot="header">{{ $route.query.id ? '试题修改' : '试题录入' }}</div>
      <el-form
        :rules="qsRules"
        ref="form"
        :model="formdata"
        label-width="120px"
      >
        <!-- 学科 -->
        <el-form-item label="学科:" prop="subjectID">
          <el-select
            @change="changeSubject"
            v-model="formdata.subjectID"
            style="width: 400px"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="formdata.catalogID" style="width: 400px">
            <el-option
              v-for="item in catalogOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 企业 选择器-->
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="formdata.enterpriseID" style="width: 400px">
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 城市 -->
        <el-form-item label="所在地区" prop="province">
          <el-select
            v-model="formdata.province"
            style="width: 198px"
            @change="getAreaOptions"
          >
            <el-option
              v-for="(item, index) in provinceList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>

          <el-select
            v-model="formdata.city"
            style="width: 198px; margin-left: 4px"
          >
            <el-option
              v-for="(item, index) in areaOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 方向 -->
        <el-form-item label="方向:" prop="direction">
          <el-select v-model="formdata.direction" placeholder="请选择">
            <el-option
              v-for="(item, index) in directionOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 题型 -->
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group
            v-model="formdata.questionType"
            @change="changeRadio({})"
          >
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value + ''"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 难度 -->
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="formdata.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value + ''"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 题干  富文本 -->
        <el-form-item label="题干：" prop="question">
          <quill-editor
            @blur="checkQustion"
            v-model="formdata.question"
            :options="editorOptions"
          ></quill-editor>
        </el-form-item>

        <!-- 选项 需要分情况和试题类型关联-->
        <el-form-item
          label="选项："
          prop="options"
          v-if="formdata.questionType !== '3'"
        >
          <div
            class="option_item"
            v-for="item in formdata.options"
            :key="item.code"
          >
            <el-radio
              v-if="formdata.questionType === '1'"
              @change="changeRadio(item)"
              v-model="item.isRight"
              style="margin-right:0"
              :label="true"
            >
              {{ item.code }}：
            </el-radio>
            <el-checkbox
              v-if="formdata.questionType === '2'"
              v-model="item.isRight"
              style="margin-right:0"
              :label="true"
            >
              {{ item.code }}：
            </el-checkbox>
            <el-input v-model="item.title" style="width:240px"></el-input>

            <el-upload
              style="margin-left:4px"
              class="avatar-uploader"
              action="http://127.0.0.1:7001"
              :headers="{ Authorization: 'Bearer ' + token }"
              :on-success="
                (res, file) => {
                  uploadSuccess(item, res, file)
                }
              "
              :show-file-list="false"
            >
              <img v-if="item.img" :src="item.img" class="avatar" />
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button
            type="danger"
            :disabled="formdata.questionType !== '2'"
            @click="addOption"
            size="small"
          >
            +增加选项与答案
          </el-button>
        </el-form-item>
        <!-- 解析视频 输入框-->
        <el-form-item label="解析视频：">
          <el-input v-model="formdata.videoURL" style="width: 400px"></el-input>
        </el-form-item>

        <!-- 答案解析 -->
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor
            @blur="checkQustion"
            v-model="formdata.answer"
            :options="editorOptions"
          ></quill-editor>
        </el-form-item>

        <!-- 题目备注 -->
        <el-form-item label="题目备注">
          <el-input
            type="textarea"
            :rows="1"
            v-model="formdata.remarks"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 题目标签 -->
        <el-form-item label="标签:">
          <el-select v-model="formdata.tags" multiple placeholder="请选择">
            <el-option
              v-for="item in tagsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 提交 -->
        <el-form-item>
          <el-button type="primary" v-if="!$route.query.id" @click="onSubmit">
            确认提交
          </el-button>
          <el-button type="primary" v-else @click="update">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { list as getCompanyOptions } from '@/api/hmmm/companys'
import { add, detail, update } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple } from '@/api/hmmm/subjects'
import { simple as getCatalogOptions } from '@/api/hmmm/directorys'
import { simple as getTagOptions } from '@/api/hmmm/tags'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

import { getToken } from '@/utils/auth'

export default {
  name: 'questions',
  components: { quillEditor },
  created() {
    this.getCityData()
    this.getSubjectAll()
    this.getCompanyOptions()
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  data() {
    return {
      // 传给富文本编辑器的值
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image'] // 上传图片
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },

      // 获取token
      token: getToken(),

      difficulty, // 难度
      questionType, // 题型

      directionOptions: direction, // 未来发展方向
      subjectList: [], // 学科列表
      provinceList: [], // 市列表
      areaOptions: [], // 区下拉框数据
      catalogOptions: [], // 目录
      enterpriseOptions: [], // 企业列表

      tagsOptions: [], // 标签选项

      formdata: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterprise: null, // 企业
        province: null, // 市
        city: null, // 区
        direction: null, // 未来方向
        questionType: '1', // 题型类别
        difficulty: '1', // 问题难度
        question: null, // 题干
        videoURL: null, // 视频解析地址
        answer: null, // 答案解析
        remarks: null, // 题目备注
        tags: null, // 标签
        id: 23,

        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },

      qsRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案', trigger: 'blur' }]
      }
    }
  },
  watch: {
    '$route.query': function() {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.formdata = {
          subjectID: null, // 学科
          catalogID: null, // 目录
          enterprise: null, // 企业
          province: null, // 市
          city: null, // 区
          direction: null, // 未来方向
          questionType: '1', // 题型类别
          difficulty: '1', // 问题难度
          question: null, // 题干
          videoURL: null, // 视频解析地址
          answer: null, // 答案解析
          remarks: null, // 题目备注
          tags: null, // 标签
          id: 23,

          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    // 修改
    update() {
      // console.log(update())
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 解构赋值
          const data = { ...this.formdata }
          // 传递数据时，需要的是字符串
          data.tags = data.tags.join(',')
          // console.log(data)
          // 发送请求
          await update(data)
          // 提示用户
          this.$message.success('修改成功')
          // 跳转
          this.$router.push('/questions/list')
        }
      })
    },
    // 提交
    onSubmit() {
      console.log(this.formdata)
      this.$refs.form.validate(async valid => {
        // console.log(valid)
        if (valid) {
          const data = { ...this.formdata }
          data.tags = data.tags.join(',')
          console.log(data)
          await add(data)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 获取题目详情
    async getQuestion() {
      // 利用路由传来的id去获取题目数据
      const { data } = await detail({ id: this.$route.query.id })

      // 切割字符串，让标签变回数组
      data.tags = data.tags.split(',')

      // 遍历选项,回显选项
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })

      // 其他数据不需要更改，直接赋值给表单
      this.formdata = data

      // 利用当前学科的值去找目录
      const res = await getCatalogOptions({
        subjectID: this.formdata.subjectID
      })
      // 获取当前目录的下拉列表
      this.catalogOptions = res.data

      // 让选中标签清空
      this.formdata.tags = null
      // 利用当前学科的值去找标签
      const res2 = await getTagOptions({ subjectID: this.formdata.subjectID })
      // 获取当前标签的下拉列表
      this.tagsOptions = res2.data

      // 赋值到最后肯定会在底部，让他滚动到顶部
      await this.$nextTick()

      window.scrollTo(0, 0)
    },

    // 选中学科或改变学科
    async changeSubject(subjectID) {
      // 让目录为空
      this.formdata.catalogID = null

      // 获取新目录
      const res = await getCatalogOptions({
        subjectID: this.formdata.subjectID
      })
      this.catalogOptions = res.data

      // 让选中标签清空
      this.formdata.tags = null
      // 获取新标签
      const res2 = await getTagOptions({ subjectID: this.formdata.subjectID })
      this.tagsOptions = res2.data

      // console.log(this.tagsOptions)
    },

    // 上传成功
    // uploadSuccess 不带括号  接收默认参数
    // uploadSuccess 带了括号  接收自己传入参数
    uploadSuccess(item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      // console.log(item, res, file)
      item.img = URL.createObjectURL(file.raw)
    },
    // 增加选项和答案
    addOption() {
      this.formdata.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.formdata.options.length),
        title: '',
        img: ''
      })
    },
    // 选择单选框 改变题型 改变难度
    changeRadio(item) {
      // 1. 清除所有的选中
      this.formdata.options.forEach(item => {
        item.isRight = false
      })
      // console.log(item)
      // 2. 自己选中
      item.isRight = true
    },
    // 校验题干,失去焦点时触发
    checkQustion() {
      // 调用el-form组件的 validateField 校验  question  字段
      this.$refs.form.validateField('question')
    },

    // 选择市，显示区
    getAreaOptions(val) {
      this.provinceList.forEach((item, index) => {
        if (val === this.provinceList[index]) {
          // console.log(citys(val))
          this.formdata.city = ''
          this.areaOptions = citys(val)
        }
      })
    },
    /// 初始化市列表
    getCityData() {
      this.provinceList = provinces()
      if (!this.province) {
        return (this.areaOptions = [])
      }
    },
    // 企业
    async getCompanyOptions() {
      const res = await getCompanyOptions({ pagesize: 10000 })
      // res.data.items 下拉选项数据  id 选项值  company 选项文字
      this.enterpriseOptions = res.data.items
    },

    // 获取学科进行渲染
    async getSubjectAll() {
      const { data } = await simple()
      // console.log(data)
      this.subjectList = data
      if (!this.subjectID) {
        return (this.enterpriseOptions = [])
      }
    }
  }
}
</script>

<style scoped lang="scss">
// 现在仅在当前组件下生效，让样式的作用更深
.question-new ::v-deep .ql-editor {
  height: 200px;
}
.question-new ::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}
.option_item {
  padding-bottom: 20px;
}
.avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
.question-new ::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.question-new ::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.question-new ::v-deep .avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
</style>
